// plan_handler
package handler

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"strings"
	"tasty/common"
	mylog "tasty/log"
)

var (
	_log = mylog.New()
)

type PLAN struct {
	ID   string `json:"id"`
	NAME string `json:"name"`
}

func PlanList(c *gin.Context) {

	_log.Add("查询数据")
	pls := make([]*PLAN, 0, 10)

	sql := `select * from plan`
	o := orm.NewOrm()
	o.Using("default")

	var ds []orm.Params
	o.Raw(sql).Values(&ds)
	for _, p := range ds {
		plan := new(PLAN)
		plan.ID = p["id"].(string)
		plan.NAME = p["name"].(string)
		pls = append(pls, plan)
	}

	data, _ := json.Marshal(pls)
	c.String(200, string(data))

	_log.Add("查询数据完成")

}

func PlanNew(c *gin.Context) {
	rs := new(common.OPT_RESULT)
	rs.CODE = "1"

	name := c.Query("name")
	comments := c.Query("comments")

	if strings.EqualFold(name, "") {
		rs.CODE = "-1"
		rs.MSG = "name is empty!"

		data, _ := json.Marshal(rs)
		c.String(200, string(data))
		return
	}

	if strings.EqualFold(comments, "") {
		rs.CODE = "-2"
		rs.MSG = "comments is empty!"
		data, _ := json.Marshal(rs)
		c.String(200, string(data))
		return
	}

	sql := `insert into plan(name, comments) values(%s, %s)`
	o := orm.NewOrm()
	o.Using("default")
	r, err := o.Raw(fmt.Sprintf(sql, name, comments)).Exec()
	if err != nil {
		rs.CODE = "-3"
		rs.MSG = err.Error()
	}

	i, er := r.RowsAffected()
	if er != nil || i <= 0 {
		rs.CODE = "-4"
		rs.MSG = err.Error()
	}

	data, _ := json.Marshal(rs)
	c.String(200, string(data))
}
